package cn.hxzy.service.impl;

import cn.hxzy.client.AuthenticationClient;
import cn.hxzy.common.ALiYunOSSProperties;
import cn.hxzy.common.Result;
import cn.hxzy.common.util.RandomId;
import cn.hxzy.entity.accreditation.TsRealNameAuthentication;
import cn.hxzy.entity.userEntity.User;
import cn.hxzy.mapper.TsRealNameAuthenticationMapper;
import cn.hxzy.service.TsRealNameAuthenticationService;
import com.aliyun.ocr20191230.Client;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;




import com.aliyun.ocr20191230.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kuizhi.Ma
 * @since 2023-06-25
 */
@Service
public class TsRealNameAuthenticationServiceImpl extends ServiceImpl<TsRealNameAuthenticationMapper, TsRealNameAuthentication> implements TsRealNameAuthenticationService {


    @Autowired
    private AuthenticationClient authenticationClient;
    @Autowired
    private ALiYunOSSProperties aLiYunOSSProperties;


    //    新增修改 马奎志
    @Override
    public Result insertRealIdCard(String phone, String idCardFront, String idCardOpposite) throws Exception {

        TsRealNameAuthentication finIdcard = new TsRealNameAuthentication();
        //判断用户是否注册
        User user = authenticationClient.selectOneByPhone(phone);
        System.out.println(user);
        if (user == null){

            return Result.error().message("请登录后再认证");
        }

        Config config = new Config();
        //你的accessKeyId
        config.accessKeyId = aLiYunOSSProperties.getAccessKeyId();
        //你的accessKeySecret
        config.accessKeySecret = aLiYunOSSProperties.getAccessKeySecret();
        config.type = "access_key";
        config.regionId = "cn-shanghai";
        Client client = new Client(config);

        TsRealNameAuthentication idcardZheng = idcardZheng(client, idCardFront);
         TsRealNameAuthentication idcardFan = idcardFan(client, idCardOpposite);
        config.endpoint = "ocr.cn-hangzhou.aliyuncs.com";


        if (idcardZheng.getIdNumber()!=null){
            finIdcard.setIdNumber(idcardZheng.getIdNumber());
            finIdcard.setAddress(idcardZheng.getAddress());
            finIdcard.setName(idcardZheng.getName());
            if(idcardZheng.getGender().equals("男")){
                finIdcard.setGender("101");
            }else{
                finIdcard.setGender("102");
            }
            finIdcard.setEthnicity(idcardZheng.getEthnicity());
            finIdcard.setBirthDate(idcardZheng.getBirthDate());
            finIdcard.setIssueAuthority(idcardZheng.getIssueAuthority());
        }else{
            idcardZheng = idcardFan(client, idCardFront);

            finIdcard.setIssueAuthority(idcardZheng.getIssueAuthority());
        }

        if (idcardFan.getIssueAuthority()!=null){
            finIdcard.setIssueAuthority(idcardFan.getIssueAuthority());

        }else{
            idcardFan = idcardFan(client, idCardOpposite);

            finIdcard.setIdNumber(idcardFan.getIdNumber());
            finIdcard.setAddress(idcardFan.getAddress());
            finIdcard.setName(idcardFan.getName());
            finIdcard.setGender(idcardFan.getGender());
            finIdcard.setEthnicity(idcardFan.getEthnicity());
            finIdcard.setBirthDate(idcardFan.getBirthDate());
            finIdcard.setIssueAuthority(idcardFan.getIssueAuthority());
        }


        //注册之后就查询认证表中的用户信息

        QueryWrapper<TsRealNameAuthentication> wrapper = new QueryWrapper<>();
        wrapper.eq("register_phone",phone);
        TsRealNameAuthentication one = super.getOne(wrapper);

        boolean save =false;
        if (one == null){
            finIdcard.setAuthenticationId(RandomId.getRealNameAuthentication());
            finIdcard.setUserId(user.getUserId());
            finIdcard.setRegisterPhone(phone);
            finIdcard.setApplyTime(new Date());
            finIdcard.setIdCardFront(idCardFront);
            finIdcard.setIdCardOpposite(idCardOpposite);
            finIdcard.setCertificationStatus(102);

            save= super.save(finIdcard);
            boolean aBoolean = authenticationClient.UpdateUserRealNameAuthentication(phone,102);
            if (save==true&& aBoolean==true){
                return Result.ok().message("管理员正在审核中").code(103);
            }else{
                return Result.error().message("101->102,失败").code(104);
            }

        }
        if (one.getCertificationStatus()==102||one.getCertificationStatus()==103){
            return Result.ok().message("管理员正在审核中，暂时不可以修改").code(102);
        }
        // 是未通过 就是修改
        if (one.getCertificationStatus()==101||one.getCertificationStatus()==104){
            UpdateWrapper<TsRealNameAuthentication> updateWrapper = new UpdateWrapper<>();

            finIdcard.setApplyTime(new Date());
            finIdcard.setIdCardFront(idCardFront);
            finIdcard.setIdCardOpposite(idCardOpposite);
            finIdcard.setCertificationStatus(102);

            updateWrapper.eq("register_phone",phone);
            save = super.update(finIdcard,updateWrapper);

            boolean aBoolean = authenticationClient.UpdateUserRealNameAuthentication(phone,102);
            if (save==true&& aBoolean==true){
                return Result.ok().message("管理员正在审核中").code(102);
            }
            return Result.error().message("101->102,修改失败").code(104);
        }

        return Result.error().message("出现一点小问题，请联系工作人员");
//        return Result.ok().message(one.getCertificationStatus()+",管理员正在审核中，暂时不能修改");
    }


    public void aaa() {

        String phone= "15535803574";
        int status=102;
        boolean aBoolean = authenticationClient.UpdateUserRealNameAuthentication(phone,status);
        if (aBoolean){
            System.out.println("ok");
        }else{
            System.out.println("no");
        }

    }






    //身份证正面
    public TsRealNameAuthentication idcardZheng(Client client, String ossUrl) throws Exception {
        String IDNumber =null;
        String address =null;
        String name =null;
        String gender =null;
        String nationality =null;
        String birthDate =null;
        String issue =null;
        TsRealNameAuthentication idcardZheng = new TsRealNameAuthentication();



        RecognizeIdentityCardRequest recognizeIdentityCardRequest = new RecognizeIdentityCardRequest()
                .setImageURL(ossUrl)
                .setSide("face");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeIdentityCardResponse recognizeIdentityCardResponse = client.recognizeIdentityCardWithOptions(recognizeIdentityCardRequest, runtime);
            System.out.println(recognizeIdentityCardResponse.getBody().getData().getFrontResult());
//            身份证正面信息：姓名（name） 性别（gender） 民族（nationality）  出生日期（birthDate）  住址（address）  公民身份证号（IDNumber）


            IDNumber = recognizeIdentityCardResponse.getBody().getData().getFrontResult().getIDNumber();
            address = recognizeIdentityCardResponse.getBody().getData().getFrontResult().getAddress();
            name = recognizeIdentityCardResponse.getBody().getData().getFrontResult().getName();
            gender = recognizeIdentityCardResponse.getBody().getData().getFrontResult().getGender();
            nationality = recognizeIdentityCardResponse.getBody().getData().getFrontResult().getNationality();
            birthDate = recognizeIdentityCardResponse.getBody().getData().getFrontResult().getBirthDate();

            idcardZheng.setIdNumber(IDNumber);
            idcardZheng.setAddress(address);
            idcardZheng.setName(name);
            idcardZheng.setGender(gender);
            idcardZheng.setEthnicity(nationality);
            idcardZheng.setBirthDate(new Date());



        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        }finally {
            return idcardZheng;
        }
    }
    //身份证反面
    public TsRealNameAuthentication idcardFan(Client client, String ossUrl) throws Exception {
        String issue =null;
        TsRealNameAuthentication idcardFan = new TsRealNameAuthentication();



        RecognizeIdentityCardRequest recognizeIdentityCardRequest = new RecognizeIdentityCardRequest()
                .setImageURL(ossUrl)
                .setSide("back");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeIdentityCardResponse recognizeIdentityCardResponse = client.recognizeIdentityCardWithOptions(recognizeIdentityCardRequest, runtime);



            issue = recognizeIdentityCardResponse.getBody().getData().getBackResult().getIssue();
            idcardFan.setIssueAuthority(issue);



        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
            System.out.println(error.message);
        }finally {
            return idcardFan;
        }
    }

}
